﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public delegate void TimerCallBack(int passSecond);

public class Timer : MonoBehaviour
{
    static Timer mInstance = null;
    public static Timer Instance
    {
        get
        {
            if (mInstance == null)
            {
                var go = new GameObject();
                mInstance = go.AddComponent<Timer>();
            }
            return mInstance;
        }
    }

    private DateTime startDate = DateTime.Now;
    private DateTime lastDate = DateTime.Now;
    private bool isRunnel = false;
    private TimerCallBack invokeFunc = null;
    private float invokeTime = 0;

    void Awake()
    {
        if (mInstance == null)
        {
            mInstance = this;
        }
    }

    public void SetCallBack(TimerCallBack invokeFunc, float invokeTime)
    {
        if (invokeFunc == null)
        {
            Debug.LogError("invokeFunc == null");
            return;
        }

        if (invokeTime <= 0)
        {
            Debug.LogError("invokeTime <= 0");
            return;
        }

        this.invokeFunc = invokeFunc;
        this.invokeTime = invokeTime;
    }

    public void Run()
    {
        if (invokeFunc == null)
        {
            Debug.LogError("invokeFunc == null  Invoke Mothod SetCallBack to set param ");
            return;
        }

        if (invokeTime <= 0)
        {
            Debug.LogError("invokeTime <= 0   Invoke Mothod SetCallBack to set param ");
            return;
        }

        isRunnel = true;
        startDate = DateTime.Now;
        lastDate = DateTime.Now;
    }

    public void Stop()
    {
        isRunnel = false;
        this.invokeFunc = null;
        this.invokeTime = 0;
    }

    void Update()
    {
        var now = DateTime.Now;
        if (!isRunnel) return;
        var val = now.Subtract(lastDate);
        if (val.TotalSeconds >= invokeTime)
        {
            lastDate = now;
            var t = now.Subtract(startDate);

            var seconds = t.Seconds;
            var day = t.Days;
            if (day > 0)
            {
                seconds += day * 86400;
            }

            var hours = t.Hours;
            if (hours > 0)
            {
                seconds += day * 3600;
            }

            var min = t.Minutes;
            if (min > 0)
            {
                seconds += min * 60;
            }
            
            this.invokeFunc(seconds);
        }
    }
}
